
async function streamToUint8Array(stream) {
    const response = new Response(stream);
    const arrayBuffer = await response.arrayBuffer();
    return new Uint8Array(arrayBuffer);
}

function uint8ArrayToStream(uint8Array) {
    return new ReadableStream({
        start(controller) {
            controller.enqueue(uint8Array);
            controller.close();
        }
    });
}

async function compress(input) {
    // 创建压缩流
    const cs = new CompressionStream('gzip');

    // 创建可写流
    const writer = cs.writable.getWriter();
    writer.write(input);
    writer.close();

    // 从压缩流读取数据
    const reader = cs.readable.getReader();
    const chunks = [];
    let totalLength = 0;

    while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        
        chunks.push(value);
        totalLength += value.length;
    }

    // 合并所有分块
    const result = new Uint8Array(totalLength);
    let offset = 0;
    for (const chunk of chunks) {
        result.set(chunk, offset);
        offset += chunk.length;
    }

    return result;
}

async function decompress(input) {
    // 创建解压流
    const ds = new DecompressionStream('gzip');

    // 创建可写流
    const writer = ds.writable.getWriter();
    writer.write(input);
    writer.close();

    // 从解压流读取数据
    const reader = ds.readable.getReader();
    const chunks = [];
    let totalLength = 0;

    while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        
        chunks.push(value);
        totalLength += value.length;
    }

    // 合并所有分块
    const result = new Uint8Array(totalLength);
    let offset = 0;
    for (const chunk of chunks) {
        result.set(chunk, offset);
        offset += chunk.length;
    }

    return result;
}

export {compress,decompress};